package cn.jiedh.app.meiweidk.homepage;


import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;

import org.xutils.ex.HttpException;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jiedh.app.meiweidk.MyWebActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.MyGridView;
import cn.jiedh.app.meiweidk.Utils.UI.MyListView;
import cn.jiedh.app.meiweidk.Utils.UI.StateLayout;
import cn.jiedh.app.meiweidk.Utils.UI.VerticalBannerView;
import cn.jiedh.app.meiweidk.Utils.db.Dbutils;
import cn.jiedh.app.meiweidk.Utils.event.Constant;
import cn.jiedh.app.meiweidk.Utils.event.EventScreen;
import cn.jiedh.app.meiweidk.Utils.event.EventUtils;
import cn.jiedh.app.meiweidk.Utils.event.Observers;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LoadUtils;
import cn.jiedh.app.meiweidk.Utils.tool.NumUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtil;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.TimeUtils;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseFragment;
import cn.jiedh.app.meiweidk.baseadapter.MyGridViewAdapter;
import cn.jiedh.app.meiweidk.baseadapter.ViewHolder;
import cn.jiedh.app.meiweidk.buried.BuriedBean;
import cn.jiedh.app.meiweidk.entity.AdMsgBean;
import cn.jiedh.app.meiweidk.entity.BannerBean;
import cn.jiedh.app.meiweidk.entity.BannerEntity;
import cn.jiedh.app.meiweidk.entity.LoanListBean;
import cn.jiedh.app.meiweidk.entity.Product;
import cn.jiedh.app.meiweidk.entity.ProductBean;
import cn.jiedh.app.meiweidk.entity.productLinkTransferBean;
import cn.jiedh.app.meiweidk.homepage.category.CategoryActivity;
import cn.jiedh.app.meiweidk.loan.LoanDetailActivity;
import cn.jiedh.app.meiweidk.login.LoginActivity;
import cn.jiedh.app.meiweidk.network.AsyncLoadImage;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.newpeopleproduct.NewPeopleProductListActivity;
import cn.jiedh.app.meiweidk.newpeopleproduct.NewProduct;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.web.WebActivity;
import cn.jiedh.app.meiweidk.welcome.SwitchStauts;

/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentHome extends BaseFragment implements Observers {

    private static final int BANNER_AUTO_TIME = 3 * 1000;//Banner自动翻页的时间

    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;


    @BindView(R.id.vertical_banner)
    VerticalBannerView verticalBanner;
    @BindView(R.id.myGridView)
    MyGridView myGridView;
    //    @BindView(R.id.tabLayout)
//    TabLayout tabLayout;
    @BindView(R.id.subGridViewHot)
    MyGridView subGridViewHot;
    @BindView(R.id.smartrefreshLayout)
    SmartRefreshLayout smartrefreshLayout;
    @BindView(R.id.successfulLoans)
    TextView successfulLoans;
    @BindView(R.id.statelayout)
    StateLayout stateLayout;
    @BindView(R.id.Hothuatilistview)
    MyListView Hothuatilistview;
    @BindView(R.id.adver1)
    ImageView adver1;
    @BindView(R.id.adver2)
    ImageView adver2;
    @BindView(R.id.adver3)
    ImageView adver3;
    @BindView(R.id.ll_newproduct_next)
    LinearLayout llNewproductNext;
    @BindView(R.id.subGridViewNew)
    MyGridView subGridViewNew;
    @BindView(R.id.ll_hotproduct)
    LinearLayout llHotproduct;
    @BindView(R.id.newmore)
    TextView newmore;
    @BindView(R.id.newmoney)
    TextView newmoney;
    @BindView(R.id.newicon)
    ImageView newicon;
    @BindView(R.id.newname)
    TextView newname;
    @BindView(R.id.newgoing)
    TextView newgoing;
    @BindView(R.id.newcontent)
    TextView newcontent;
    @BindView(R.id.ll_newpeople)
    LinearLayout llNewpeople;
    @BindView(R.id.ll_adver1)
    LinearLayout llAdver1;
    @BindView(R.id.ll_adver2)
    LinearLayout llAdver2;
    @BindView(R.id.ll_adver3)
    LinearLayout llAdver3;
    @BindView(R.id.hotmore)
    TextView hotmore;
    Unbinder unbinder;
    @BindView(R.id.ll_newhave)
    LinearLayout llNewhave;
    @BindView(R.id.rl_hotproduct)
    RelativeLayout rlHotproduct;
    @BindView(R.id.rl_newproduct)
    RelativeLayout rlNewproduct;
    @BindView(R.id.rl_hotactivity)
    RelativeLayout rlHotactivity;
    @BindView(R.id.ll_DKnum)
    LinearLayout llDKnum;

    @BindView(R.id.green_land)
    ImageView green_land;//绿色通道
    private List<BannerEntity> mBannerEntitys = new ArrayList<>();//banner
    private List<AdMsgBean.AdMsgEnity> adMsgBeanList = new ArrayList<>();//动态消息
    private List<Product> mHotProducts = new ArrayList<>();//主要热点推荐
    private List<LoanListBean.DataList> ProductsNew = new ArrayList<>();//新品推荐
    private List<LoanListBean.DataList> ProductsHot = new ArrayList<>();//热门推荐
    private BannerEntity bannerEntity;//banner详情

    private List<BuriedBean> buriedList;

    private List<HotActivityBean> huatilist = new ArrayList<>();
    private int newProductPage = 1;
    private int HotProductPage = 1;
    private boolean IsOpenNewexclusive = false;
    private MyGridViewAdapter HotlistAdapter;
    private Dbutils dbutils;

    public FragmentHome() {
        // Required empty public constructor
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view) {
        dbutils = new Dbutils();
        EventUtils.getDefault().register(this);
        initBanner();
        initMsg();
        initProduct();
        initGroom();
        initHotHuati();
        stateLayout.setOnNoClick(new StateLayout.NoNetView() {
            @Override
            public void setOnclck(View view) {
                reLoad();
            }
        });
        smartrefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        smartrefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        stateLayout.netviewGone();
                        newProductPage = 1;
                        HotProductPage = 1;
                        reLoad();
                        refreshlayout.finishRefresh();
                        refreshlayout.setLoadmoreFinished(false);
                    }
                }, 2000);
            }
        });
        smartrefreshLayout.autoRefresh();
    }


    /**
     * 绿色通道开关
     */
    private void getGreenSwitch() {
        Map<String, Object> map = new HashMap<>();

        request(UrlUtils.GREEN_LAND, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse<String> response) {
                if (response.getCode() == 0) {//code=0 开
                    green_land.setVisibility(View.VISIBLE);
                } else {
                    green_land.setVisibility(View.GONE);
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                green_land.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 热门话题
     */
    private void initHotHuati() {
        HotlistAdapter = new MyGridViewAdapter<HotActivityBean>(getActivity(), R.layout.hothuati_tiem, huatilist) {
            @Override
            public void convert(ViewHolder helper, HotActivityBean item, int position) {
                if (!TextUtils.isEmpty(item.getNickname())) {
                    helper.setText(R.id.htname, item.getNickname());
                } else if (TextUtils.isEmpty(item.getNickname()) && !TextUtils.isEmpty(item.getMobilePhone())) {
                    helper.setText(R.id.htname, "手机用户" + StringUtils.get4num(item.getMobilePhone()));
                } else {
                    helper.setText(R.id.htname, "手机用户xxxx");
                }
                helper.setImageByUrBig(R.id.htimg, item.getUserImgUrl());
                helper.setText(R.id.httime, TimeUtils.gettime(item.getCreateTime()));
                helper.setText(R.id.httitle, item.getTitle());
                helper.setText(R.id.htcontent, item.getDigest());
                if (TextUtils.isEmpty(item.getImgUrl())) {
                    helper.getView(R.id.hticon).setBackgroundResource(R.mipmap.wd_tx);
                } else {
                    helper.setImageByUrBig(R.id.hticon, item.getImgUrl());
                }
                if (item.getReadCount() > 9999) {
                    helper.setText(R.id.readnum, 9999 + "+");
                } else {
                    helper.setText(R.id.readnum, item.getReadCount() + "");
                }
                if (item.getCommentCount() > 9999) {
                    helper.setText(R.id.plnum, 9999 + "+");
                } else {
                    helper.setText(R.id.plnum, item.getCommentCount() + "");
                }

                helper.getView(R.id.huatiitem).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MobclickAgent.onEvent(getActivity(), "home_hotRecommend");
                        MobclickAgent.onEvent(getActivity(), "home_hotTopic");
                        SPUtils.saveBuried("click", "0", "首页-热门话题-" + item.getTitle(), "",
                            "首页-热门话题", "", "", "");
                        WebActivity.launch(item.getH5link() + "?id=" + item.getRaidersId(), "社区详情", getActivity());
                        EventScreen eventScreen = new EventScreen("gowebactivity", "");
                        EventUtils.getDefault().forward(eventScreen);
//                        if(position==0){
//                            collect("17",null,null);
//                        }else{
//                            collect("18",null,null);
//                        }
                    }
                });
            }
        };
        Hothuatilistview.setAdapter(HotlistAdapter);
    }

    /**
     * 首页热门活动
     */
    public void refreshHotRM() {
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", "1");
        map.put("pageSize", "100");
        map.put("type", "2");
        request(UrlUtils.MAINRM, map, true, new ResponseSuccess<HotActivityDate>() {
            @Override
            public void onRequestSucceed(BaseResponse<HotActivityDate> response) {
                if (response.getCode() == 0 && response.getData().getDataList() != null && response.getData().getDataList().size() > 0) {
                    huatilist.clear();
                    huatilist.addAll(response.getData().getDataList());
                    HotlistAdapter.notifyDataSetChanged();
                    rlHotactivity.setVisibility(View.VISIBLE);
                } else {
                    rlHotactivity.setVisibility(View.GONE);
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                rlHotactivity.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 刷新页面
     */
    void reLoad() {

        if (SPUtils.getIsLogin()) {//登陆了才刷新数据
//            getGreenSwitch();
            refreshBanner();
            refreshMsg();
            refreshProduct();
            refreshGroom();
            refreshHotRM();
//            getadver1();
//            getadver2();
//            getadver3();
//            if (SPUtils.getIsLogin()) {
//                isNewexclusive();
//            } else {
//                IsOpenNewexclusive = false;
//                llNewpeople.setVisibility(View.GONE);
//            }
        } else {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isGoHome", true);
            ActivityUtil.next(getActivity(), LoginActivity.class, bundle);

        }


    }

    @Override
    protected void initData() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        unbinder = ButterKnife.bind(this, super.onCreateView(inflater, container, savedInstanceState));
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    /**
     * 初始化banner
     */
    private void initBanner() {
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, mBannerEntitys)
            .setPageIndicator(new int[]{R.drawable.dot2, R.drawable.dot})
            .setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    MobclickAgent.onEvent(getActivity(), "banner" + (position + 1)); //Umeng
                    buriedList = new ArrayList<BuriedBean>();
                    buriedList.add(new BuriedBean("click", "首页banner", "2", mBannerEntitys.get(position).getBannerId() + "", "", "首页", "false", "", "", "", "", "", "", "", "", "", ""));
                    SPUtils.saveBuriedList(buriedList);
                    if (mBannerEntitys.get(position).getType() != 0) {//banner类型 0不可点击 1外链 2内链
                        if (mBannerEntitys.get(position).getType() == 1) {
                            Bundle bundle = new Bundle();
                            bundle.putString("url", "");
                            bundle.putString("title", mBannerEntitys.get(position).getName());
                            bundle.putInt("id", mBannerEntitys.get(position).getBannerId());
                            bundle.putInt("source", 1);
                            ActivityUtil.next(getActivity(), MyWebActivity.class, bundle);
                            collect("8",null,null);
                        } else {
                            //内联
                            getBannerDetail(mBannerEntitys.get(position).getBannerId());
                        }
                    }


                }
            })
            .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
    }

    /**
     * 获取banner 详细信息
     */
    private void getBannerDetail(int bannerId) {
        Map map = new HashMap<String, Objects>();
        map.put("bannerId", bannerId);
        request(UrlUtils.BANNERDETAIL, map, false, new ResponseSuccess<BannerEntity>() {
            @Override
            public void onRequestSucceed(BaseResponse<BannerEntity> response) {
                if (response.getCode() == 0) {
                    bannerEntity = response.getData();
                    if (bannerEntity != null) {
                        toProductDetail(bannerEntity.getInId(), bannerEntity.getName());
                    }
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化banner错误" + msg);
                T.showShortToast(msg);
            }
        });
    }

    /**
     * 获取banner数据
     */
    private void refreshBanner() {
        Map map = new HashMap<String, Objects>();
        map.put("type", "0");

        request(UrlUtils.BANNER, map, false, new ResponseSuccess<BannerBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<BannerBean> response) {
                if (response.getCode() == 0 && response.getData().getDataList().size() > 0) {
                    convenientBanner.setVisibility(View.VISIBLE);
                    mBannerEntitys.clear();
                    mBannerEntitys.addAll(response.getData().getDataList());
                    llDKnum.setVisibility(View.VISIBLE);
                    successfulLoans.setVisibility(View.VISIBLE);
                    successfulLoans.setText(NumUtils.getDivideNum(response.getData().getSuccessfulLoans() + ""));
                    convenientBanner.notifyDataSetChanged();
                } else {
                    llDKnum.setVisibility(View.GONE);
                    convenientBanner.setVisibility(View.GONE);
                    mBannerEntitys.clear();
                    convenientBanner.notifyDataSetChanged();
                    successfulLoans.setVisibility(View.GONE);
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化banner错误" + msg);
                T.showShortToast(msg);
                llDKnum.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 初始化滚动消息
     */
    private void initMsg() {
        verticalBanner.setItemView(R.layout.layout_good_roll);
        verticalBanner.setViewHolder(new VerticalBannerView.ViewHolder<AdMsgBean.AdMsgEnity>() {
            @Override
            public void initView(AdMsgBean.AdMsgEnity adMsgBean, View view) {
                view.setTag(adMsgBean);
                TextView productNameTv = (TextView) view.findViewById(R.id.product_name_tv);
                TextView contentTv = (TextView) view.findViewById(R.id.content_tv);
                ImageView logoIv = (ImageView) view.findViewById(R.id.logo_iv);
                productNameTv.setText(adMsgBean.getName());
                if (getActivity() != null && !isDetached()) {

                    LoadUtils.loadImage(getActivity(), adMsgBean.getImgUrl(), logoIv);

//                    Glide.with(getActivity()).load(adMsgBean.getImgUrl()).placeholder(R.drawable.green_loading).error(R.drawable.load_fail).into(logoIv);
                    contentTv.setText(Html.fromHtml(String.format(getString(R.string.ad_msg_content), adMsgBean.getContent(), adMsgBean.getMoney())));
                }
//                view.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        MobclickAgent.onEvent(getActivity(), "main_msg");
//                        SPUtils.saveBuried("click", "0", "首页-滚动消息入口-" + adMsgBean.getName(), "",
//                                "首页-滚动消息入口", "", "", adMsgBean.getProductId() + "");
//                        toProductDetail(adMsgBean.getProductId(), adMsgBean.getName());
//                    }
//                });
            }
        });
    }

    /**
     * 获取滚动消息
     */
    void refreshMsg() {
        Map map = new HashMap<String, Objects>();
        request(UrlUtils.ROLL_MSG, map, false, new ResponseSuccess<AdMsgBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<AdMsgBean> response) {
                if (response.getData().getDataList() != null && response.getData().getDataList().size() > 0) {
                    adMsgBeanList.clear();
                    adMsgBeanList.addAll(response.getData().getDataList());
                    verticalBanner.setVisibility(View.VISIBLE);
                    verticalBanner.stop();
                    verticalBanner.setDatas(adMsgBeanList);
                    verticalBanner.start();
                } else {
                    verticalBanner.setVisibility(View.GONE);
                }

            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化滚动消息错误" + msg);
                T.showShortToast(msg);
                if (verticalBanner != null) {
                    verticalBanner.setVisibility(View.GONE);
                }

            }
        });
    }


    /**
     * 初始化固定产品
     */
    MyGridViewAdapter baseAdapter;
    private static final String TAG = "FragmentHome";

    private void initProduct() {
        GradientDrawable background = (GradientDrawable) getResources().getDrawable(R.drawable.bg_home_hot);
        background.setColor(getResources().getColor(R.color.actionsheet_blue));
        baseAdapter = new MyGridViewAdapter<Product>(this.getActivity(), R.layout.layout_home_hot, mHotProducts) {
            @Override
            public void convert(ViewHolder helper, Product item, int position) {

                Log.d(TAG, position + "项 ImgUrl 的数据:" + item.getImgUrl());
                Log.d(TAG, position + "项 name 的数据：" + item.getName());
                Log.d(TAG, position + "项hot_ad 的数据：" + item.getExplain());

                helper.setImageByUrMini(R.id.home_hot_bgiv, item.getImgUrl());
                helper.setText(R.id.home_hot_name, item.getName());
//                helper.setText(R.id.home_hot_ad, item.getExplain());
                helper.setOnClickListener(R.id.home_hot_bg, new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        SPUtils.saveBuried("click", "0", "首页-卡片位-列表-" + item.getName(), "",
                            "首页-卡片位", "", "", item.getIndexSearchId() + "");
                        MobclickAgent.onEvent(getActivity(), "type" + (position + 1));  //umeng
                        MobclickAgent.onEvent(getActivity(), "home_class_" + (position + 1));
                        MobclickAgent.onEvent(getActivity(), "home_card_click");
                        Bundle bundle = new Bundle();
                        bundle.putInt("indexSearchId", item.getIndexSearchId());
                        bundle.putString("title", item.getName());
                        bundle.putInt("type", item.getType());//1APP原生 2 H5
                        ActivityUtil.next(getActivity(), CategoryActivity.class, bundle);
                        collect("0",item.getIndexSearchId()+"",null);
                    }
                });
            }
        };
        myGridView.setAdapter(baseAdapter);
    }

    /**
     * 获取固定产品
     */
    private void refreshProduct() {
        Map map = new HashMap<String, Objects>();
        request(UrlUtils.HOME_PRODUCT, map, false, new ResponseSuccess<ProductBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<ProductBean> response) {
                mHotProducts.clear();
                mHotProducts.addAll(response.getData().getDataList());
                baseAdapter.notifyDataSetChanged();
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.showShortToast(msg);
            }
        });
    }

    /**
     * 初始化新品和热门推荐
     */
    MyGridViewAdapter subAdapterNew;
    MyGridViewAdapter subAdapterHot;
    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");

    private void initGroom() {
        //最新
        subAdapterNew = new MyGridViewAdapter<LoanListBean.DataList>(getActivity(), R.layout.layout_home_groom, ProductsNew) {
            @Override
            public void convert(ViewHolder helper, LoanListBean.DataList item, int position) {
                helper.setImageByUrBig(R.id.home_groom_iv, item.getImgUrl());
                helper.setText(R.id.home_groom_name, item.getName());

                TextView ad = helper.getView(R.id.home_groom_ad);
                String moneyMax = item.getMoneyMax() + "";
                String monyMin = item.getMoneyMin() + "";
                if (moneyMax.length() >= 6) {
                    moneyMax = item.getMoneyMax() / 10000 + "万";
                } else {
                    moneyMax = item.getMoneyMax() + "";
                }

                if (monyMin.length() >= 6) {
                    monyMin = item.getMoneyMin() / 10000 + "万";
                } else {
                    monyMin = item.getMoneyMin() + "";
                }
//                ad.setText(Html.fromHtml(String.format(getString(R.string.home_groom_max), moneyMax)));
                ad.setText(monyMin + "-" + moneyMax);

                TextView rate_type_tv = helper.getView(R.id.rate_type_tv);
                TextView loan_daily_rate = helper.getView(R.id.loan_daily_rate);
                TextView loan_success_rate = helper.getView(R.id.loan_success_rate);
                TextView loan_advert = helper.getView(R.id.loan_advert);


                if (item.getRateType() == 1) {
                    rate_type_tv.setText("参考月利率");
                } else {
                    rate_type_tv.setText("参考日利率");
                }

                loan_daily_rate.setText(item.getRate() + "%");
                loan_success_rate.setText(decimalFormat.format(Double.parseDouble(item.getSuccessRate())) + "%");

                String advert = "贷款额度可达<font color='#F5A623'>" + item.getMoneyMax() + "</font>";
                loan_advert.setText(Html.fromHtml(advert));


                TextView goApply_tv = helper.getView(R.id.goApply_tv);
                goApply_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        apply(item.getProductId(), item.getApplyUrl(), item.getName());
                    }
                });

            }
        };
        subGridViewNew.setAdapter(subAdapterNew);
        subGridViewNew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                MobclickAgent.onEvent(getActivity(), "home_newRecommend");
                MobclickAgent.onEvent(getActivity(), "newproduct" + (i + 1)); //umeng
                SPUtils.saveBuried("click", "0", "首页-新品推荐-" + ProductsNew.get(i).getName(), "",
                    "首页-新品推荐", "", "", "");
                toProductDetail(ProductsNew.get(i).getProductId(), ProductsNew.get(i).getName());
            }
        });

        //热门
        subAdapterHot = new MyGridViewAdapter<LoanListBean.DataList>(this.getActivity(), R.layout.layout_home_groom, ProductsHot) {
            @Override
            public void convert(ViewHolder helper, LoanListBean.DataList item, int position) {
                helper.setImageByUrBig(R.id.home_groom_iv, item.getImgUrl());
                helper.setText(R.id.home_groom_name, item.getName());
                TextView ad = helper.getView(R.id.home_groom_ad);
                String moneyMax = item.getMoneyMax() + "";
                String monyMin = item.getMoneyMin() + "";
                if (moneyMax.length() >= 6) {
                    moneyMax = item.getMoneyMax() / 10000 + "万";
                } else {
                    moneyMax = item.getMoneyMax() + "";
                }

                if (monyMin.length() >= 6) {
                    monyMin = item.getMoneyMin() / 10000 + "万";
                } else {
                    monyMin = item.getMoneyMin() + "";
                }
//                ad.setText(Html.fromHtml(String.format(getString(R.string.home_groom_max), moneyMax)));
                ad.setText(monyMin + "-" + moneyMax);

                TextView loan_daily_rate = helper.getView(R.id.loan_daily_rate);
                TextView loan_success_rate = helper.getView(R.id.loan_success_rate);
                TextView loan_advert = helper.getView(R.id.loan_advert);


                if (item.getRateType() == 1) {
                    loan_daily_rate.setText("参考月利率:"+item.getRate() + "%");
                } else {
                    loan_daily_rate.setText("参考日利率:"+item.getRate() + "%");
                }


                loan_success_rate.setText("通过率高达"+decimalFormat.format(Double.parseDouble(item.getSuccessRate())) + "%");

                String advert = "贷款额度可达<font color='#F5A623'>" + item.getMoneyMax() + "</font>";
//                loan_advert.setText(Html.fromHtml(advert));
                loan_advert.setText(item.getAdver());
                TextView goApply_tv = helper.getView(R.id.goApply_tv);
                goApply_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        apply(item.getProductId(), item.getApplyUrl(), item.getName());
                    }
                });
            }
        };
        subGridViewHot.setAdapter(subAdapterHot);
        subGridViewHot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                MobclickAgent.onEvent(getActivity(), "hotproduct" + (i + 1)); //umeng
                SPUtils.saveBuried("click", "0", "首页-热门推荐-" + ProductsHot.get(i).getName(), "",
                    "首页-热门推荐", "", "", "");
                toProductDetail(ProductsHot.get(i).getProductId(), ProductsHot.get(i).getName());
            }
        });
    }


    /**
     * 统计并跳转
     *
     * @param productId
     * @param applyUrl
     * @param loanTitle
     */
    private void apply(int productId, String applyUrl, String loanTitle) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("productId", productId + "");
        request(UrlUtils.ADDBROWSE, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                dismissLoadingDialog();
                if (0 == response.getCode()) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString("url", applyUrl);
//                    bundle.putString("title", loanTitle);
//                    Intent intent = new Intent(getActivity(), MyWebActivity.class);
//                    intent.putExtras(bundle);
//                    startActivityForResult(intent, 1);
                    productLinkTransfer(productId, applyUrl, loanTitle);
                } else {
                    T.showShort(response.getMessage());
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.show(msg);
                dismissLoadingDialog();
            }
        });
    }

    /**
     * 是否是联合登陆的产品
     */
    private void productLinkTransfer(int productId, String applyUrl, String loanTitle) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("productId", productId + "");
        request(UrlUtils.PRODUCT_LINK_TRANSFER, map, false, new ResponseSuccess<productLinkTransferBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<productLinkTransferBean> response) {
                dismissLoadingDialog();
                Intent intent = new Intent(getActivity(), MyWebActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("title", loanTitle);
                if (0 == response.getCode()) {
                    bundle.putString("url", response.getData().getApplyUrl());
                } else {
                    bundle.putString("url", applyUrl);
                }
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.show(msg);
                dismissLoadingDialog();
            }
        });
    }


    public void refreshNewproduct() {
        //新品推荐
        Map map = new HashMap<String, Objects>();
        map.put("moneyMin", 0);//最小金额(搜索条件,0为不传)
        map.put("moneyMax", 0);//最大金额(搜索条件,0为不传)
        map.put("term", 0);//贷款期限(搜索条件,0为不传)
        map.put("typeId", 0);//类型ID(搜索条件,0为不传)
        map.put("newWhether", 1);//是否新品 1为是(搜索条件,0为不传)
        map.put("hotWhether", 0);//是否热门 1为是(搜索条件,0为不传)
        map.put("sort", 0);//0 默认后台排序 1成功率 2贷款利率 3贷款速度 4额度由高到低 5额度由低到高
        map.put("pageNo", newProductPage);//第几页
        map.put("pageSize", "4");//每页几条

        request(UrlUtils.NEW_HOT, map, false, new ResponseSuccess<LoanListBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<LoanListBean> response) {
                if (response.getCode() == 0) {
                    ProductsNew.clear();
                    if (response.getData().getDataList().size() == 0 && newProductPage > 1) {
                        newProductPage = 1;
                        refreshNewproduct();
                        rlNewproduct.setVisibility(View.VISIBLE);
                    } else {
                        ProductsNew.addAll(response.getData().getDataList());
                        subAdapterNew.notifyDataSetChanged();
                        rlNewproduct.setVisibility(View.VISIBLE);
                    }
                } else {
                    rlNewproduct.setVisibility(View.GONE);
                    T.showShortToast(response.getMessage());
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化获取新品错误" + msg);
                T.showShortToast(msg);
                rlNewproduct.setVisibility(View.GONE);
            }
        });
    }

    public void refreshHotProduct() {
        //热门推荐
        Map map2 = new HashMap<String, Objects>();
        map2.put("moneyMin", 0);//最小金额(搜索条件,0为不传)
        map2.put("moneyMax", 0);//最大金额(搜索条件,0为不传)
        map2.put("term", 0);//贷款期限(搜索条件,0为不传)
        map2.put("typeId", 0);//类型ID(搜索条件,0为不传)
        map2.put("newWhether", 0);//是否新品 1为是(搜索条件,0为不传)
        map2.put("hotWhether", 1);//是否热门 1为是(搜索条件,0为不传)
        map2.put("sort", 0);//0 默认后台排序 1成功率 2贷款利率 3贷款速度 4额度由高到低 5额度由低到高
        map2.put("pageNo", HotProductPage);//第几页
        map2.put("pageSize", "4");//每页几条

        request(UrlUtils.NEW_HOT, map2, false, new ResponseSuccess<LoanListBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<LoanListBean> response) {
                if (response.getCode() == 0) {
                    ProductsHot.clear();
                    if (response.getData().getDataList().size() == 0 && HotProductPage > 1) {
                        HotProductPage = 1;
                        refreshHotProduct();
                        rlHotproduct.setVisibility(View.VISIBLE);
                    } else {
                        ProductsHot.addAll(response.getData().getDataList());
                        subAdapterHot.notifyDataSetChanged();
                        rlHotproduct.setVisibility(View.VISIBLE);
                    }
                } else {
                    rlHotproduct.setVisibility(View.GONE);
                    T.showShortToast(response.getMessage());
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化热门推荐错误" + msg);
                T.showShortToast(msg);
                rlHotproduct.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 获取新品和热门推荐
     */
    public void refreshGroom() {
//        refreshNewproduct();
        refreshHotProduct();
    }

    /**
     * 跳转到产品详情页
     *
     * @param productId 产品id
     */
    private void toProductDetail(int productId, String title) {

//        apply(productId);

        Bundle bundle = new Bundle();
        bundle.putInt("productId", productId);
        bundle.putString("title", title);
        ActivityUtil.next(getActivity(), LoanDetailActivity.class, bundle);
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (SPUtils.getIsLogin()) {
//            isNewexclusive();
//        }
        verticalBanner.start();
        convenientBanner.startTurning(BANNER_AUTO_TIME);
        MobclickAgent.onResume(getActivity());
    }

    @Override
    public void onStop() {
        super.onStop();
        verticalBanner.stop();
        convenientBanner.stopTurning();
        MobclickAgent.onResume(getActivity());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    List<BannerEntity> adver1list = new ArrayList<>();
    List<BannerEntity> adver2list = new ArrayList<>();
    List<BannerEntity> adver3list = new ArrayList<>();
    BannerEntity adver1bean;
    BannerEntity adver2bean;
    BannerEntity adver3bean;

    //广告位请求
    public void getadver1() {
        Map map = new HashMap<String, Objects>();
        map.put("type", "2");
        request(UrlUtils.BANNER, map, false, new ResponseSuccess<BannerBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<BannerBean> response) {
                if (response.getCode() == 0 && response.getData().getDataList().size() > 0) {
                    adver1list.clear();
                    adver1list.addAll(response.getData().getDataList());
                    adver1bean = adver1list.get(0);
                    AsyncLoadImage.loadImage(adver1bean.getImgUrl(), adver1);
                    llAdver1.setVisibility(View.VISIBLE);
                } else {
                    llAdver1.setVisibility(View.GONE);
                    adver1list.clear();
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化adver1错误" + msg);
                T.showShortToast(msg);
            }
        });
    }

    public void getadver2() {
        Map map = new HashMap<String, Objects>();
        map.put("type", "3");
        request(UrlUtils.BANNER, map, false, new ResponseSuccess<BannerBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<BannerBean> response) {
                if (response.getCode() == 0 && response.getData().getDataList().size() > 0) {
                    adver2list.clear();
                    adver2list.addAll(response.getData().getDataList());
                    adver2bean = adver2list.get(0);
                    AsyncLoadImage.loadImage(adver2bean.getImgUrl(), adver2);
                    llAdver2.setVisibility(View.VISIBLE);
                } else {
                    llAdver2.setVisibility(View.GONE);
                    adver2list.clear();
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化adver1错误" + msg);
                T.showShortToast(msg);
            }
        });
    }

    public void getadver3() {
        Map map = new HashMap<String, Objects>();
        map.put("type", "4");
        request(UrlUtils.BANNER, map, false, new ResponseSuccess<BannerBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<BannerBean> response) {
                if (response.getCode() == 0 && response.getData().getDataList().size() > 0) {
                    adver3list.clear();
                    adver3list.addAll(response.getData().getDataList());
                    adver3bean = adver3list.get(0);
                    AsyncLoadImage.loadImage(adver3bean.getImgUrl(), adver3);
                    llAdver3.setVisibility(View.VISIBLE);
                } else {
                    llAdver3.setVisibility(View.GONE);
                    adver3list.clear();
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化adver1错误" + msg);
                T.showShortToast(msg);
            }
        });
    }

    @OnClick({R.id.adver1, R.id.adver2, R.id.adver3, R.id.ll_newproduct_next, R.id.newmore, R.id.ll_hotproduct, R.id.hotmore, R.id.ll_newhave, R.id.green_land})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_newproduct_next:
                newProductPage++;
//                refreshNewproduct();
                break;
            case R.id.ll_hotproduct:
                HotProductPage++;
                refreshHotProduct();
                break;
            case R.id.newmore:  //点击新人专享更多
                MobclickAgent.onEvent(getActivity(), "home_newbie_checkMore");
                SPUtils.saveBuried("click", "0", "首页-新人专享-更多推荐-列表", "",
                    "首页-新人专享-更多推荐", "", "", "");
                Bundle bundle = new Bundle();
                bundle.putString("money", SPUtils.getMoney());
                ActivityUtil.next(getActivity(), NewPeopleProductListActivity.class, bundle);
                break;
            case R.id.ll_newhave:  //点击新人专享立即申请

//                apply(newProductList.get(0).getProductId());
                MobclickAgent.onEvent(getActivity(), "home_newbie_detail");
                if (newProduct != null) {
                    SPUtils.saveBuried("click", "0", "首页-新人专享-立即申请-详情", "", "首页-新人专享-立即申请",
                        SPUtils.getMoney(), SPUtils.getType(), newProduct.getProductId() + "");
                    Bundle bundle1 = new Bundle();
                    bundle1.putInt("productId", newProduct.getProductId());
                    ActivityUtil.next(getActivity(), LoanDetailActivity.class, bundle1);
                }
                break;
            case R.id.adver1:
                if (adver1bean != null) {
                    MobclickAgent.onEvent(getActivity(), "home_botomAdver_1");
                    SPUtils.saveBuried("click", "3", "首页广告位点击1", "",
                        "首页-广告位点击-1", "", "", "");
                    if (adver1bean.getType() != 0) {//banner类型 0不可点击 1外链 2内链
                        if (adver1bean.getType() == 1) {
                            Bundle b = new Bundle();
                            b.putString("url", "");
                            b.putString("title", adver1bean.getName());
                            b.putInt("id", adver1bean.getBannerId());
                            b.putInt("source", 1);
                            ActivityUtil.next(getActivity(), MyWebActivity.class, b);
                            collect("10",null,null);
                        } else {
                            //内联
                            getBannerDetail(adver1bean.getBannerId());
                        }
                    }

                }
                break;
            case R.id.adver2:
                if (adver2bean != null) {
                    MobclickAgent.onEvent(getActivity(), "home_botomAdver_2");
                    SPUtils.saveBuried("click", "3", "首页广告位点击2", "",
                        "首页-广告位点击-2", "", "", "");
                    if (adver2bean.getType() != 0) {//banner类型 0不可点击 1外链 2内链
                        if (adver2bean.getType() == 1) {
                            Bundle b = new Bundle();
                            b.putString("url", "");
                            b.putString("title", adver2bean.getName());
                            b.putInt("id", adver2bean.getBannerId());
                            b.putInt("source", 1);
                            ActivityUtil.next(getActivity(), MyWebActivity.class, b);

                            collect("11",null,null);
                        } else {
                            //内联
                            getBannerDetail(adver2bean.getBannerId());
                        }
                    }

                }

                break;
            case R.id.adver3:
                if (adver3bean != null) {
                    MobclickAgent.onEvent(getActivity(), "home_botomAdver_3");
                    SPUtils.saveBuried("click", "3", "首页广告位点击3", "",
                        "首页-广告位点击-3", "", "", "");
                    if (adver3bean.getType() != 0) {//banner类型 0不可点击 1外链 2内链
                        if (adver3bean.getType() == 1) {
                            Bundle b = new Bundle();
                            b.putString("url", "");
                            b.putString("title", adver3bean.getName());
                            b.putInt("id", adver3bean.getBannerId());
                            b.putInt("source", 1);
                            ActivityUtil.next(getActivity(), MyWebActivity.class, b);
                            collect("12",null,null);
                        } else {
                            //内联
                            getBannerDetail(adver3bean.getBannerId());

                        }
                    }

                }
                break;
            case R.id.hotmore:
                MobclickAgent.onEvent(getActivity(), "home_hotTopic_more");
                SPUtils.saveBuried("click", "0", "首页-热门话题-更多热门话题-列表", "",
                    "首页-热门话题-更多热门话题", "", "", "");
                EventScreen eventScreen = new EventScreen("gowebactivity", "");
                EventUtils.getDefault().forward(eventScreen);
                break;

            case R.id.green_land://绿色通道
                MobclickAgent.onEvent(getActivity(), "green_land_click");
                ActivityUtil.next(getActivity(), GreenLandActivity.class);
                collect("4",null,null);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventUtils.getDefault().unregister(this);
    }

    @Override
    public void update(Object obj) {
//        if ((obj instanceof EventScreen)) {
//            EventScreen eventScreen = (EventScreen) obj;
//            if (eventScreen.getType().equals(Constant.NEWUSER)) {
//                L.d("进入首页-------", "==========================");
//                isNewexclusive();
//            } else if (eventScreen.getType().equals(Constant.LOGINOUT)) {
//                if (llNewpeople != null) {
//                    llNewpeople.setVisibility(View.GONE);
//                }
//
//            }
//
//        }
    }

    /**
     * 是否开启新人专享开关接口
     */
    public void isNewexclusive() {
        Map<String, Object> map = new HashMap<>();
        map.put("type", "0");
        request(UrlUtils.SwitchStatus, map, true, new ResponseSuccess<SwitchStauts>() {
            @Override
            public void onRequestSucceed(BaseResponse<SwitchStauts> response) {
                if (response.getCode() == 0) {
                    if (response.getData().isStatus()) {
                        CheckRegisterTimeExtended();
                    } else {
                        IsOpenNewexclusive = false;
                        llNewpeople.setVisibility(View.GONE);
                    }
                } else {
                    IsOpenNewexclusive = false;
                    llNewpeople.setVisibility(View.GONE);
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                IsOpenNewexclusive = false;
                llNewpeople.setVisibility(View.GONE);
            }
        });
    }

    //新人专区展示-判断注册时间
    public void CheckRegisterTimeExtended() {
        Map<String, Object> map = new HashMap<>();
        request(UrlUtils.CheckRegisterTimeExtended, map, true, new ResponseSuccess<SwitchStauts>() {
            @Override
            public void onRequestSucceed(BaseResponse<SwitchStauts> response) {
                if (response.getCode() == 0) {
                    if (response.getData().isFlag()) {
                        Newexclusive();
                    } else {
                        IsOpenNewexclusive = false;
                        llNewpeople.setVisibility(View.GONE);
                    }
                } else {
                    IsOpenNewexclusive = false;
                    llNewpeople.setVisibility(View.GONE);
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                IsOpenNewexclusive = false;
                llNewpeople.setVisibility(View.GONE);
            }
        });
    }

    List<NewProduct> newProductList = new ArrayList<>();
    NewProduct newProduct = null;

    /**
     * 新人专享数据接口
     */
    private void Newexclusive() {
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", "1");
        map.put("pageSize", "1");
        map.put("money", SPUtils.getMoney());
//        map.put("money", "10000");
        request(UrlUtils.GetNewExclusiveProductList, map, true, new ResponseSuccess<NewProductData>() {
            @Override
            public void onRequestSucceed(BaseResponse<NewProductData> response) {
                if (response.getCode() == 0) {
                    if (response.getData() != null) {
                        newProductList.clear();
                        newProductList.addAll(response.getData().getDataList());
                        if (newProductList.size() > 0) {
                            newProduct = newProductList.get(0);
                            initNewexclusive(newProduct, response.getData().getReason());
                        } else {
                            initNewexclusive(null, response.getData().getReason());
                        }
                    } else {
                        IsOpenNewexclusive = false;
                        llNewpeople.setVisibility(View.GONE);
                    }
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                IsOpenNewexclusive = false;
                llNewpeople.setVisibility(View.GONE);
            }
        });
    }

    //加载新人专享数据
    private void initNewexclusive(NewProduct newProduct, String Reason) {
        if (newProduct != null) {
            IsOpenNewexclusive = true;
            llNewpeople.setVisibility(View.VISIBLE);
            newmoney.setText(SPUtils.getMoney());
            AsyncLoadImage.loadImageMethodOne(newProduct.getImgUrl(), newicon);
            newname.setText(newProduct.getName());
            newcontent.setText(Reason);
        } else if (llNewpeople.getVisibility() == View.VISIBLE) {
            IsOpenNewexclusive = true;
            newmoney.setText(SPUtils.getMoney());
        } else {
            IsOpenNewexclusive = false;
            llNewpeople.setVisibility(View.GONE);
        }
    }


    /**
     * 功能统计
     *
     * @param type      类型
     * @param collectId type为0和19时collectId不为空
     * @param url       有就传
     */
    private void collect(String type, String collectId, String url) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        if (null != collectId) {
            map.put("collectId", collectId);
        }
        if (null != url) {
            map.put("url", url);
        }
        request(UrlUtils.COLLECT, map, true, new ResponseSuccess<NewProductData>() {
            @Override
            public void onRequestSucceed(BaseResponse<NewProductData> response) {
            }
        });
    }


}
